package net.xdclass.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author MissZhou
 */
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private NotifyService notifyService;

    /**
     * 图形验证码10分钟有效时间
     */
    private static final long CAPTCHA_CODE_EXPRIED = 60*1000*10;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @ApiOperation("获取图像验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        String text = captchaProducer.createText();
        log.info("图形验证码:{}",text);
        //存储key
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request),text,CAPTCHA_CODE_EXPRIED, TimeUnit.MILLISECONDS);
        BufferedImage bufferedImage = captchaProducer.createImage(text);
        ServletOutputStream outputStream = null;
        try{
            outputStream=response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        }catch (IOException e){
            log.error("获取图形验证码异常:{}",e);
        }
    }


    /**
     * 发送验证码
     * 1. 匹配验证码是否正确
     * 2. 发送验证码
     * @param to
     * @param captcha
     * @return
     */
    @ApiOperation("发送验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to",required = true) String to,
                                        @RequestParam(value = "captcha",required = true) String captcha,
                                     HttpServletRequest request){

        String key = getCaptchaKey(request);
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(key);
        //匹配图形验证码是否一样
        if (captcha != null && cacheCaptcha != null && cacheCaptcha.equals(captcha)) {
            //成功
            stringRedisTemplate.delete(key);
            //发送验证码
            return notifyService.sendCode(SendCodeEnum.USER_REGISTER, to);
        }else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }

    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("user-Agent");
        String key = "user-service:captcha:"+ CommonUtil.MD5(ipAddr+userAgent);
        log.info("ip={}",ipAddr);
        log.info("userAgent={}",userAgent);
        log.info("key={}",key);
        return  key;

    }
}
